package biz.bbtec.sbm.email.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.omg.CORBA.DATA_CONVERSION;

import biz.bbtec.sbm.db.dbConnection;
import biz.bbtec.sbm.email.action.MyAuthenticator;
import biz.bbtec.sbm.email.bean.MailSenderInfo;
import biz.bbtec.sbm.issuetracking.bean.TaskBean;
import biz.bbtec.sbm.issuetracking.bean.WorkBean;
import biz.bbtec.sbm.user.bean.UserBean;

public class EmailAlarmService {

	dbConnection db = new dbConnection();
	
	public  void mailsend(MailSenderInfo mailInfo){
		 
		 MyAuthenticator authenticator = null;
		  Properties pro = mailInfo.getProperties();
		  //如果需要身份认证，则创建一个密码验证器  
		  if (mailInfo.isValidate()) { 
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		  } 
		  // 根据邮件会话属性和密码验证器构造一个发送邮件的session 
		  Session sendMailSession = Session.getDefaultInstance(pro,authenticator); 
		  try { 
		  // 根据session创建一个邮件消息 
		  Message mailMessage = new MimeMessage(sendMailSession); 
		  // 创建邮件发送者地址 
		  Address from = new InternetAddress(mailInfo.getFromAddress()); 
		  // 设置邮件消息的发送者 
		  mailMessage.setFrom(from); 
		  // 创建邮件的接收者地址，并设置到邮件消息中 
		  Address to = new InternetAddress(mailInfo.getToAddress()); 
		  // Message.RecipientType.TO属性表示接收者的类型为TO 
		  mailMessage.setRecipient(Message.RecipientType.TO,to); 
		  // 设置邮件消息的主题 
		  mailMessage.setSubject(mailInfo.getSubject()); 
		  // 设置邮件消息发送的时间 
		  mailMessage.setSentDate(new Date()); 
		  // MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象 
		  Multipart mainPart = new MimeMultipart(); 
		  // 创建一个包含HTML内容的MimeBodyPart 
		  BodyPart html = new MimeBodyPart(); 
		  // 设置HTML内容 
		  html.setContent(mailInfo.getContent(), "text/html; charset=utf-8"); 
		  mainPart.addBodyPart(html); 
		  // 将MiniMultipart对象设置为邮件内容 
		  mailMessage.setContent(mainPart); 
		  // 发送邮件 
		  Transport.send(mailMessage); 
		
		  } catch (MessagingException ex) { 
			  ex.printStackTrace(); 
		  } 
		  
		} 
    

	public List userlist() {
	
		List<UserBean> list = new ArrayList<UserBean>();
        Date date=new Date();
        int hour=date.getHours();
		String sql1 = "select userid,email,name from user where alertstate=1 and alerttime="+hour;
		Connection conn = db.getConnection();
		PreparedStatement past = null;
		ResultSet rs = null;

		try {
			past = conn.prepareStatement(sql1);
			rs = past.executeQuery();
			while (rs.next()) {
				UserBean user = new UserBean();
				user.setUserid(rs.getInt(1));
				user.setEmail(rs.getString(2));
				user.setName(rs.getString(3));
				list.add(user);
			}
			rs.close();
			past.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.closeConnection(conn);
		}
		return list;
	}

	public List<TaskBean> tasklist(int userid) {
		List<TaskBean> list = new ArrayList<TaskBean>();
		String sql1 = "select task.taskid,task.name from task,taskaccess where task.taskid = taskaccess.taskid and taskaccess.userid = ?";

		Connection conn = db.getConnection();
		PreparedStatement past = null;
		ResultSet rs = null;

		try {
			past = conn.prepareStatement(sql1);
			past.setInt(1, userid);
			rs = past.executeQuery();
			while (rs.next()) {
				TaskBean task = new TaskBean();
				task.setTaskid(rs.getInt(1));
				task.setName(rs.getString(2));
				list.add(task);
			}
			rs.close();
			past.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.closeConnection(conn);
		}
		return list;
	}

	public List<WorkBean> worklist(int userid, int taskid) {
		List<WorkBean> list = new ArrayList<WorkBean>();

		String sql = "select workpackage.title,workpackage.wpid,workpackage.deadline from "
				+ "workpackage,workpackageallocation where workpackage.wpid = workpackageallocation.wpid and "
				+ "workpackageallocation.userid = ? and workpackage.taskid = ? and workpackage.progress<100";

		Connection conn = db.getConnection();
		PreparedStatement past = null;
		ResultSet rs = null;
		try {
			past = conn.prepareStatement(sql);
			past.setInt(1, userid);
			past.setInt(2, taskid);
			rs = past.executeQuery();
			while (rs.next()) {
				WorkBean work = new WorkBean();
				work.setTitle(rs.getString(1));
				work.setWpid(rs.getInt(2));
				work.setDeadline(rs.getString(3));
				list.add(work);
			}
			rs.close();
			past.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.closeConnection(conn);
		}
		return list;
	}

	public List check(List<WorkBean> work) throws ParseException {
		List<WorkBean> list = new ArrayList<WorkBean>();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		for (int i = 0; i < work.size(); i++) {
			/*
			if (work.get(i).getDeadline().trim().equalsIgnoreCase("")) {
				System.out.println("empty");
				continue;
			}*/
			if(work.get(i).getDeadline()==null)
			{
				continue;
			}
			if(work.get(i).getDeadline().trim().equalsIgnoreCase(""))
			{
				continue;
			}
			
			Date test = sdf.parse(work.get(i).getDeadline().trim());
			if (test.before(date)) {
				list.add(work.get(i));  //逾期
			} else {
				long diff = test.getTime() - date.getTime();
				long days = diff / (1000 * 60 * 60 * 24);
				if (days <= 2) {
					list.add(work.get(i));   //快到期的
				}
			}
		}
		return list;
	}
	
	public UserBean User(int userid){
		
		UserBean user = new UserBean();
		
		Connection conn = db.getConnection();
		PreparedStatement past = null;
		ResultSet rs = null;
		
		String sql = "select * from user where userid = ?";
		try {
			past = conn.prepareStatement(sql);
			past.setInt(1, userid);
			rs = past.executeQuery();
			if (!(rs.next())) {
				return null;
			}
			user.setUserid(rs.getInt("userid"));
			user.setName(rs.getString("name"));
			user.setEmail(rs.getString("email"));
			
			rs.close();
			past.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			db.closeConnection(conn);
		}
		
		return user;
		
	}
	
}
